<?php
defined("BASEPATH") OR exit("No direct script access allowed");

class XunJianChose extends CI_Controller
{
    private $appId;
    private $appSecret;
    private $compName;
    private $tableName;


    /**
     * XunJian constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->appId = "wwc6bba99e4709d99c";
        $this->appSecret = "22JHgq9o-SshfwrrOK76p5DcakUZmIJwgBC7STdXo4w";
        $this->compName = "容百科技";
        $this->tableName = "weixininfo_rb";
    }

    public function index($userid){

        /*$userid = "6522";
        $jsapiTicket = $this->getJsApiTicket();
        // 注意 URL 一定要动态获取，不能 hardcode.
        $protocol = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off" || $_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";

        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
        //var_dump($jsapiTicket);
        $signature = sha1($string);

        $signPackage = array(
            "appId"     => $this->appId,
            "nonceStr"  => $nonceStr,
            "timestamp" => $timestamp,
            "url"       => $url,
            "signature" => $signature,
            "rawString" => $string,
            "userid"    => $userid,
            "createTime"=> time()
        );*/
        $username = "";
        $position = "";
        if(strlen($userid) > 0){
            $access_token = $this->get_access_token();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$userid;
            $res = json_decode($this->http_request_json($url));
            $username = $res->name;
            $position = $res->position;

            //获取部门名称
//            $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$access_token."&id=".$departmentId;
//            $deptres = json_decode($this->http_request_json($url));
//            $deptName = $deptres->department;
//            $deptName = $deptName['name'];

            $data = array(
                "userid" => $userid,
                "username" => $username,
                "position" => $position
            );
            $this->load->view("XunJianChose",$data);
        }else{
            $this->load->view("XunJianChose");
        }

    }

    public function gotoindex(){
        $userid = $_REQUEST["userid"];
        if(strlen($userid) > 0){
            $access_token = $this->get_access_token();
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/get?access_token=".$access_token."&userid=".$userid;
            $res = json_decode($this->http_request_json($url));
            $username = $res->name;
            $position = $res->position;

            //获取部门名称
//            $url = "https://qyapi.weixin.qq.com/cgi-bin/department/list?access_token=".$access_token."&id=".$departmentId;
//            $deptres = json_decode($this->http_request_json($url));
//            $deptName = $deptres->department;
//            $deptName = $deptName['name'];

            $data = array(
                "userid" => $userid,
                "username" => $username,
                "position" => $position
            );
            $this->load->view("XunJianChose",$data);
        }else{
            $this->load->view("XunJianChose");
        }
    }
//    public function index(){
//
//        /*$userid = "6522";
//        $jsapiTicket = $this->getJsApiTicket();
//        // 注意 URL 一定要动态获取，不能 hardcode.
//        $protocol = (!empty($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] !== "off" || $_SERVER["SERVER_PORT"] == 443) ? "https://" : "http://";
//        $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
//
//        $timestamp = time();
//        $nonceStr = $this->createNonceStr();
//
//        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
//        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
//        //var_dump($jsapiTicket);
//        $signature = sha1($string);
//
//        $signPackage = array(
//            "appId"     => $this->appId,
//            "nonceStr"  => $nonceStr,
//            "timestamp" => $timestamp,
//            "url"       => $url,
//            "signature" => $signature,
//            "rawString" => $string,
//            "userid"    => $userid,
//            "createTime"=> time()
//        );*/
//
//        $this->load->view("XunJianChose");
//    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新，以下代码以写入到文件中做示例
        //$data = json_decode(file_get_contents("weixinJS/jsapi_ticket.json"));
        $data = $this->Data_model->get_single_data(array("type" => "jsapi_ticket","compname" => $this->compName),$this->tableName);
        if ($data["time"] < time() || $data === null) {
            $accessToken = $this->get_access_token();
            // 如果是企业号用以下 URL 获取 ticket
            $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken";
            //$url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->http_request_json($url));
            $ticket = $res->ticket;
            //var_dump($ticket);
            if ($ticket) {
                if($data === null){
                    $this->Data_model->add_data(array("compname" => $this->compName,"type" => "jsapi_ticket","jsapi_ticket" => $ticket),$this->tableName);
                }else{
                    $this->Data_model->update_data(array("type" => "jsapi_ticket"),array("time" => time() + 7000,"jsapi_ticket" => $ticket),$this->tableName);
                }

                /*
                        $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("weixinJS/jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
                 *
                 */
            }
        } else {
            $ticket = $data["jsapi_ticket"];
        }
        return $ticket;
    }

    function get_access_token(){
        $result = $this->Data_model->get_single_data(array("compname"=>$this->compName,"type"=>"access_token"),$this->tableName);
        if($result["time"] < time() || $result === null){
            $corpid = $result["corpid"];
            $corpsecret = $result["corpsecret"];
            if($result === null){
                $corpid = $this->appId;
                $corpsecret = $this->appSecret;
            }
            $url="https://qyapi.weixin.qq.com/cgi-bin/gettoken?&corpid=".$corpid."&corpsecret=".$corpsecret;
            
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data["access_token"])){
                if($result === null){
                    $this->Data_model->add_data(array("compname"=>$this->compName,"corpid" => $this->appId,"corpsecret" => $this->appSecret,"type"=>"access_token","access_token" => $data["access_token"]),$this->tableName);
                }else{
                    $this->Data_model->update_data(array("compname"=>$this->compName,"type"=>"access_token"),array("access_token" => $data["access_token"],"time" => time()+7000),$this->tableName);
                }
                $access_token = $data["access_token"];
            }else{
                return "获取access_token错误";
            }
        }else{
            $access_token = $result["access_token"];
        }
        return $access_token;
    }

    function http_request_json($url){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        curl_close($ch);
        return $result;
    }

    public function Login(){
        if (isset($_GET['code'])){
            $code = $_GET['code'];
            $res = $this->Data_model->get_single_data(array('compname' => $this->compName,'type'=>'xunjian'),$this->tableName);
            $res_access = $this->Data_model->get_single_data(array('compname' => $this->compName,'type'=>'access_token'),$this->tableName);
            $this->get_userId($res_access['access_token'], $code,$res['agentid']);
        }else{
            echo "NO CODE";
        }
    }

    function get_userId($access_token,$code,$agentId){
        if($access_token){
            $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
            $json=self::http_request_json($url);//这个地方不能用file_get_contents
            $data=json_decode($json,true);
            if(isset($data['errcode']) & $data['errcode'] != 0){
                if($data['errcode'] == "40001" or $data['errcode'] == '42001' or $data['errcode'] == '40014' or $data['errcode'] == '40029'){
                    $this->get_access_token();

                    /*
                    $url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=".$access_token."&code=".$code."&agentid=".$agentId;
					$json=self::http_request_json($url);//这个地方不能用file_get_contents
					$data=json_decode($json,true);
					$this->index($data['UserId']);

                     *
                     */
                    $newurl = "<?=base_url()?>/XunJianChose/Login?code=".$code;
                    echo "<script language='javascript' type='text/javascript'>";
                    echo "window.location.href='".$newurl."'";
                    echo "</script>";

                }else{
                    echo "页面请求错误，请检查！";
                }
            }else{
                $this->index($data['UserId']);
            }
        }else{
            $this->get_access_token();
            $this->Login();
        }
    }

}